/**
* Module: 
* Description: 商品管理
* Author: xsq
* Date: 2023/05/03 14:25:30
* LastEditAuthor: xsq
* LastEditTime: 2023/05/03 14:25:30
*/
<template>
  <div class="content">
    <div class="breadcrumb">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="search">
      <el-form ref="ruleFormRef" :inline="true" :model="queryParams.params" :rules="rules" class="demo-form-inline">
        <!-- <el-form-item label="账号分类" prop="commodity_cate_id">
          <el-select v-model="queryParams.params.commodity_cate_id" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in commodityCates"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="标题" prop="title" class="form-item-width">
          <el-input v-model="queryParams.params.title" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="手机号" prop="phone" class="form-item-width">
          <el-input v-model="queryParams.params.phone" placeholder="请输入" />
        </el-form-item> -->

        <!-- <el-form-item label="商品id" prop="account_id">
          <el-input v-model="queryParams.params.account_id" placeholder="请输入" />
        </el-form-item> -->

        <el-form-item label="发布客服" prop="number" class="form-item-width" v-if="getSession('userInfo')?.id == 1">
          <el-select v-model="queryParams.params.admin_user_id" filterable placeholder="发布客服">
            <el-option
              v-for="item in adminList"
              :key="item.id"
              :label="item.realname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- <el-form-item label="账号编号" prop="number">
          <el-input v-model="queryParams.params.number" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="开通橱窗" prop="shop_status" class="form-item-width">
          <el-select v-model="queryParams.params.shop_status" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in dictMap['shop:window:status']"
              :key="item.dict_item_id"
              :label="item.dict_item_title"
              :value="item.dict_item_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="粉丝画像" prop="fans_bias" class="form-item-width">
          <el-select v-model="queryParams.params.fans_bias" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in dictMap['fan:bias']"
              :key="item.dict_item_id"
              :label="item.dict_item_title"
              :value="item.dict_item_id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="价格" prop="price">
          <el-select v-model="queryParams.params.price" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in dictMap['price:range']"
              :key="item.dict_item_id"
              :label="item.dict_item_title"
              :value="item.dict_item_id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="价格" class="form-item-width">
          <div class="range-input">
            <el-input v-model="queryParams.params.price_min" placeholder="请输入" />
            <span class="range-separator">-</span>
            <el-input v-model="queryParams.params.price_max" placeholder="请输入" />
          </div>
        </el-form-item>

        <el-form-item label="有无实名" prop="auth_status" class="form-item-width">
          <el-select v-model="queryParams.params.auth_status" class="m-2" placeholder="请选择">
            <el-option
              v-for="item in dictMap['authentication:status']"
              :key="item.dict_item_id"
              :label="item.dict_item_title"
              :value="item.dict_item_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="粉丝量" class="form-item-width">
          <div class="range-input">
            <el-input v-model="queryParams.params.fans_min" placeholder="万" />
            <span class="range-separator">-</span>
            <el-input v-model="queryParams.params.fans_max" placeholder="万" />
          </div>
        </el-form-item>
        <!-- <el-form-item label="日期" class="form-item-width date-item-width">
          <div class="range-input">
            <el-date-picker v-model="queryParams.params.startTime" value-format="YYYY/MM/DD" format="YYYY-MM-DD" type="date" placeholder="开始日期"></el-date-picker>
            <span class="range-separator">-</span>
            <el-date-picker v-model="queryParams.params.endTime" value-format="YYYY/MM/DD" format="YYYY-MM-DD" type="date" placeholder="结束日期"></el-date-picker>
          </div>
        </el-form-item> -->

        <el-form-item label="出售状态" prop="sale_status" class="form-item-width">
          <el-select v-model="queryParams.params.sale_status" class="m-2" placeholder="请选择">
            <el-option
              label="在售中"
              value="1"
            />
            <el-option
              label="交接中"
              value="2"
            />
            <el-option
              label="已售出"
              value="3"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="账号类目" prop="category" class="form-item-width">
          <el-select v-model="queryParams.params.category" class="m-2" placeholder="请选择" filterable>
            <el-option
              v-for="item in dictMap['goods:category']"
              :key="item.dict_item_id"
              :label="item.dict_item_title"
              :value="item.dict_item_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上架人" prop="admin_user_id" class="form-item-width" v-if="isAdminAuth">
          <el-select v-model="queryParams.params.admin_user_id" class="m-2" placeholder="请选择" filterable>
            <el-option
              v-for="item in adminList"
              :key="item.id"
              :label="item.realname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否上架" prop="status" class="form-item-width">
          <el-select 
            v-model="queryParams.params.status" 
            multiple 
            class="m-2" 
            placeholder="请选择"
            @change="handleStatusChange"
          >
            <el-option
              label="上架"
              :value="1"
            />
            <el-option
              label="下架"
              :value="0"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item class="form-item-btn">
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            搜索
          </el-button>
          <el-button type="primary" @click="addHandle" v-auth="'commodity:add'">添加账号</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- <div class="operation">
      <el-button type="primary" @click="addHandle" v-auth="'commodity:add'">添加账号</el-button>
    </div> -->

    <el-table class="table-box" :data="tableData" stripe style="width: 100%" table-layout="fixed">
      <el-table-column prop="title" label="标题">
        <template #default="scope">
          <el-icon v-if="scope.row.is_hot == 1" :style="{'font-size': '20px', 'color': 'red'}"><magic-stick /></el-icon>
          {{ scope.row.title }}
          <!-- <a @click.prevent="goDetail(scope.row.id)" :href="`http://www.hqs168.cn/listDetail/${scope.row.id}`" target="_blank">
            {{ scope.row.title }}
          </a> -->
        </template>
      </el-table-column>
      <!-- <el-table-column prop="commodity_cate_id" label="账号类型">
        <template #default="scope">
          {{ commodityCates.find(item => item.id == scope.row.commodity_cate_id)?.title }}
        </template>
      </el-table-column> -->
      <el-table-column prop="category" label="账号类目">
        <template #default="scope">
          <span v-if="scope.row.category != ''">
            <el-tag class="ml-2" v-for="tag in scope.row.category?.split(',').map(item => getDictNameVal(dicts, item))">{{
              tag }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="auth_status" label="认证状态">
        <template #default="scope">
          {{ getDictNameVal(dictMap['authentication:status'], scope.row.auth_status) }}
        </template>
      </el-table-column>
      <el-table-column prop="fans_num" label="粉丝量(万)" width="100">
        <template #default="scope">
          {{ scope.row.fans_num }}万
        </template>
      </el-table-column>
      <el-table-column prop="shop_status" label="粉丝画像">
        <template #default="scope">
          {{ getDictNameVal(dictMap['fan:bias'], scope.row.fans_bias) }}
        </template>
      </el-table-column>
      <el-table-column prop="shop_status" label="粉丝年龄">
        <template #default="scope">
          {{ getDictNameVal(dictMap['fan:age'], scope.row.fans_age) }}
        </template>
      </el-table-column>
      <el-table-column prop="shop_status" label="橱窗状态">
        <template #default="scope">
          {{ getDictNameVal(dictMap['shop:window:status'], scope.row.shop_status) }}
        </template>
      </el-table-column>
      <el-table-column prop="chart_auth" label="星图权限">
        <template #default="scope">
          {{ getDictNameVal(dictMap['starChart:auth'], scope.row.chart_auth) }}
        </template>
      </el-table-column>
      <el-table-column prop="has_violation" label="有无违规">
        <template #default="scope">
          {{ getDictNameVal(dictMap['violation'], scope.row.has_violation) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="售价(元)" width="100" />
      <el-table-column prop="min_price" label="低价(元)" width="100" />

      <el-table-column prop="status" label="是否上架">
        <template #default="scope">
          {{ scope.row.status ? '上架' : '下架' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="上架人">
        <template #default="scope">
          {{ scope.row.admin_user_name }}
        </template>
      </el-table-column>

      <el-table-column prop="chart_auth" label="创建时间">
        <template #default="scope">
          <!-- {{ formatTime(new Date(scope.row.create_time * 1000), 'm-d') }} -->
          {{ dayjs(scope.row.create_time).format('MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column prop="visit_time" label="回访时间">
        <template #default="scope">
          {{ dayjs(scope.row.visit_time).format('MM-DD') }}
        </template>
      </el-table-column>

      <!-- <el-table-column prop="is_hot" label="是否热门">
        <template #default="scope">
          {{ scope.row.is_hot ? '是' : '否' }}
        </template>
      </el-table-column> -->
      
      
      
      <!-- <el-table-column prop="chart_real" label="星图实名">
        <template #default="scope">
          {{ getDictNameVal(dictMap['starChart:realname'], scope.row.chart_real) }}
        </template>
      </el-table-column> -->
      
      <!-- <el-table-column prop="status" label="是否上架">
        <template #default="scope">
          {{ scope.row.status ? '上架' : '下架' }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="sale_status" label="出售状态">
        <template #default="scope">
          {{ scope.row.sale_status == 1 ? '在售中' 
          : scope.row.sale_status == 2 ? '交接中' 
          : scope.row.sale_status == 3 ? '已售出' 
          : '' }}
        </template>
      </el-table-column> -->
      <el-table-column prop="reason_remark" label="下架理由">
        <template #default="scope">
          {{ scope.row.reason_remark }}
        </template>
      </el-table-column>
      
      
      <el-table-column fixed="right" label="操作" width="260">
        <template #default="scope">
          <el-popover
            v-if="scope.row.status == 1"
            v-model="isShowPopover"
            placement="right"
            width="400"
            trigger="click">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入下架理由"
              v-model="reasonRemark">
            </el-input>
            <el-button
              type="primary"
              size="small"
              @click="changeStatus(scope.row)"
            >
              确认
            </el-button>
            <!-- <el-button
              type="text"
              size="small"
              @click="changeIsShowPopover()"
            >
              取消
            </el-button> -->
            <template #reference>
              <el-button text type="primary" size="small" v-auth="'commodity:status'">
                {{ scope.row.status == 1 ? '下架' : '上架' }}
              </el-button>
            </template>
          </el-popover>

          <el-button 
            text type="primary" 
            size="small" 
            @click="changeStatus(scope.row)"
            v-auth="'commodity:status'"
            v-if="scope.row.status != 1"
            >
            {{ scope.row.status == 1 ? '下架' : '上架' }}
          </el-button>
          <!-- <el-button text type="warning" size="small" @click="changeHot(scope.row)"
            v-auth="'commodity:hot'">
            {{ scope.row.is_hot == 1 ? '取消热门' : '设置热门' }}
          </el-button> -->
          <el-button text type="primary" size="small" @click="editHandle(scope.row)" v-auth="'commodity:edit'">
            编辑
          </el-button>

          <el-button text type="primary" size="small" @click="reviewHandle(scope.row)">
            查看
          </el-button>
          <el-button text type="primary" size="small" @click="delHandle(scope.row)" v-auth="'commodity:del'">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="total" :key="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getTableData" :total="total" :pageSizes="[1, 10, 20, 30]"></Pagination>
  </div>
</template>

<script setup lang="ts">
import config from '/@/config/index';
import { reactive, ref, unref, getCurrentInstance, watch, computed } from 'vue';
import { useTableList } from '/@/hooks/useTable';
import { Pagination } from '/@/components/Pagination/index';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { formatTime, getSession, encrypt } from '/@/utils/index';
import dayjs from 'dayjs';

const route = useRoute();

watch(
  () => route.params,
  (val: any) => {
    queryParams.params.commodity_cate_id = val.id;
    getTableData();
  },
);

// 是否有管理员查看权限
const isAdminAuth = computed(() => {
  const authList = getSession('auth');
  const isAuth = authList.findIndex(item => item.name == 'commodity:admin:list'); // 是否有管理员查看权限
  return isAuth != -1 ? true : false;
})

const { proxy }: any = getCurrentInstance();
const tableData: any[] = reactive([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  params: {
    admin_user_id: getSession('userInfo')?.id != 1 ? getSession('userInfo')?.id : '',
    status: [1, 0],
    title: '',
    phone: '', // 手机号
    account_id: '', // 商品id
    number: '', // 编号
    shop_status: '', // 橱窗状态
    fans_bias: '', // 粉丝偏向
    price: '',
    price_min: '', // 价格
    price_max: '', // 价格
    fans_min: '', // 粉丝数量
    fans_max: '', // 粉丝数量
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    commodity_cate_id: route.params.id ? route.params.id : '' ,
    sale_status: '', // 出售状态
    auth_status: '', // 认证状态
    category: '', // 账号类目
    user_id: '', // 上架人
  },
  reasonRemark: '', // 下架理由
});
const reasonRemark = ref('');
const isShowPopover = ref(false);

const total = ref(0);

const router = useRouter();

const changeIsShowPopover = () => {
  reasonRemark.value = '';
  isShowPopover.value = !isShowPopover.value;
};

const addHandle = () => {
  return router.push({
    path: '/commodity/add',
    query: {
      cateId: route.params.id
    }
  });
};

// NOTE:编辑账号
const editHandle = (rows) => {
  return router.push({
    path: '/commodity/add',
    query: {
      id: encrypt(rows.id).replace(/\//g, '~'),
      cateId: rows.commodity_cate_id
    }
  });
};

// NOTE:编辑账号
const reviewHandle = (rows) => {
  return router.push({
    path: '/commodity/add',
    query: {
      id: encrypt(rows.id).replace(/\//g, '~'),
      cateId: rows.commodity_cate_id,
      review: 1
    }
  });
};

// NOTE:删除账号
const delHandle = (rows) => {
  const id = rows.id;
  ElMessageBox.confirm('确定是否删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await proxy.$http.deleteCommodityById({ id });

    if (res.code == config.SUCCESS_CODE) {
      ElMessage({
        message: '操作成功！',
        type: 'success',
      });
      getTableData();
    }
  });
}

const dicts = reactive<any[]>([]);
const dictMap = reactive({});
// NOTE:查询字典
const getDicts = async () => {
  const res = await proxy.$http.getDicts({
    dictMap: [
      'goods:category', // 类目
      'authentication:status', // 认证状态
      'price:range', // 价格区间
      'fan:bias', // 粉丝偏向
      'fan:age', // 粉丝年龄
      'fan:num', // 粉丝数量
      'shop:window:status', // 橱窗状态
      'violation', // 有无违规
      'starChart:realname', // 星图实名
      'starChart:auth', // 星图权限
      'live:auth', // 直播权限
    ]
  });
  if (res.code == config.SUCCESS_CODE) {
    dicts.push(...res.data);
    for (let i = 0; i < res.data.length; i++) {
      dictMap[res.data[i].name] = res.data[i].items;
    }
  }
};

// NOTE:获取字典值
const getDictNameVal = (dicts: any[], id: number): string => {
  let i = dicts?.length || 0;
  while (i--) {
    if (dicts[i].items) {
      let items = dicts[i].items;
      for (let j = 0; j < items.length; j++) {
        if (items[j].dict_item_id == id) {
          return items[j].dict_item_title;
        }
      }
    } else {
      if (dicts[i].dict_item_id == id) {
        return dicts[i].dict_item_title;
      }
    }
  }
  return '';
};

// 查询账户列表数据
const getTableData = () => {
  useTableList(proxy.$http.getCommodityList, queryParams, res => {
    tableData.length = 0;
    tableData.push(...res.tableData);
    total.value = unref(res.total);
  });
};

// 查询角色
const adminList: any[] = reactive([]);
const getAdminList = async () => {
  const res = await proxy.$http.getAdminList({
    pageSize: 999,
    pageNum: 1
  });
  if (res.code == config.SUCCESS_CODE) {
    adminList.length = 0;
    adminList.push(...res.data.datas);
    console.log('admin', adminList);

    console.log('userInfo', getSession('userInfo'))
  }
};

const commodityCates = reactive<any[]>([]); // 账号分类
// NOTE:查询账号分类
const commodityCateList = async () => {
  const res = await proxy.$http.commodityCateList();
  if (res.code == config.SUCCESS_CODE) {
    commodityCates.length = 0;
    commodityCates.push(...res.data);
  }
};

// NOTE:设置热门
const changeHot = async (rows) => {
  const isHot = rows.is_hot ? 0 : 1;
  const res = await proxy.$http.changeCommodityHot({
    id: rows.id,
    is_hot: isHot
  });
  if (res.code == config.SUCCESS_CODE) {
    ElMessage({
      message: '操作成功！',
      type: 'success',
    });
    getTableData();
  }
};

// NOTE:设置上架状态
const changeStatus = async (rows) => {
  const status = rows.status ? 0 : 1;

  // 下架时校验是否填写理由
  if (status === 0 && !reasonRemark.value) {
    return ElMessage({
      message: '请填写下架理由',
      type: 'warning'
    });
  }

  // 如果是下架操作且有下架理由
  const params = {
    id: rows.id,
    status: status,
    reason_remark: ''
  };
  
  // 下架时需要添加下架理由
  if (status === 0 && reasonRemark.value) {
    params.reason_remark = reasonRemark.value;
  }

  const res = await proxy.$http.changeCommodityStatus(params);
  if (res.code == config.SUCCESS_CODE) {
    ElMessage({
      message: '操作成功！',
      type: 'success',
    });
    // 清空下架理由
    reasonRemark.value = '';
    // 关闭弹窗
    isShowPopover.value = false;
    getTableData();
  }
};


const rules = reactive<FormRules>({});
const ruleFormRef = ref<FormInstance>();

// 重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  queryParams.params.price_min = '';
  queryParams.params.price_max = '';
  queryParams.params.fans_min = '';
  queryParams.params.fans_max = '';
  queryParams.params.startTime = '';
  queryParams.params.endTime = '';
};

const handleStatusChange = (selectedValues: number[]) => {
  if (selectedValues.length === 0) {
    // 如果没有选中任何选项，则强制选中一个默认值（例如上架）
    // queryParams.params.status = [1];
    // 恢复到之前的值
    queryParams.params.status = queryParams.params.status.length > 0 ? queryParams.params.status : [1];
    return ElMessage({
      message: '至少保留一个状态',
      type: 'error',
    });
  }
};

// 提交搜索表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      getTableData();
    }
  });
};

const init = () => {
  // const authList = getSession('auth');
  // const isAuth = authList.findIndex(item => item.name == 'commodity:admin:list'); // 是否有管理员查看权限
  // if (isAuth != -1) {
  //   queryParams.params.admin_user_id = '';
  // }
  // 如果是管理员取消限制
  if (isAdminAuth.value) {
    queryParams.params.admin_user_id = '';
  }

  getTableData();
  getDicts();
  commodityCateList();
  getAdminList();
};

init();

// 跳转详情
const goDetail = (value: number | string) => {
  const id = encrypt(value).replace(/\//g, '~');
  return window.open(`https://www.hqs168.cn/listDetail/${id}`, '_blank');
}
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  .operation {
    margin: 10px 0;
  }
  .el-breadcrumb {
    margin-bottom: 15px;
  }

  // 添加搜索条件宽度一致的样式
  .form-item-width {
    width: 280px;
    margin-right: 10px;
    
    :deep(.el-form-item__content) {
      width: calc(100% - 80px); // 减去label的宽度
    }
    
    :deep(.el-select) {
      width: 100%;
    }

    // 添加范围输入框的样式
    .range-input {
      display: flex;
      align-items: center;
      width: 100%;
      
      :deep(.el-input) {
        flex: 1;
      }
      
      .range-separator {
        margin: 0 5px;
      }
    }
  }

  // 日期选择器特殊宽度
  .date-item-width {
    width: 460px; // 更宽的日期选择器
    
    :deep(.el-form-item__content) {
      width: calc(100% - 80px);
    }
    
    .range-input {
      :deep(.el-date-picker) {
        width: 180px;
      }
    }
  }
}
</style>